/**
 * 区域代理后台模拟数据
 */
import { format } from 'date-fns';

// 转化漏斗项目接口
interface ConversionFunnelItem {
  stage: string;
  count: number;
  conversionRate?: number;
}

// 随机数生成工具函数
const randomNum = (min: number, max: number): number => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

// 金额格式化
const formatMoney = (amount: number): string => {
  return amount.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
};

// 随机生成指定长度的ID
const generateId = (prefix: string, length: number = 6): string => {
  const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = prefix;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

// 随机选择数组中的一个元素
const randomPick = <T>(arr: T[]): T => {
  return arr[Math.floor(Math.random() * arr.length)];
};

// 随机生成状态
const randomStatus = (): string => {
  const statuses = ['active', 'inactive'];
  return randomPick(statuses);
};

// 随机生成提现状态
const randomWithdrawalStatus = (): string => {
  const statuses = ['pending', 'approved', 'rejected', 'completed'];
  return randomPick(statuses);
};

// 随机生成订单状态
const randomOrderStatus = (): string => {
  const statuses = ['pending', 'processing', 'shipping', 'completed', 'canceled'];
  return randomPick(statuses);
};

// 随机生成头像
const randomAvatar = (): string => {
  const id = Math.floor(Math.random() * 1000);
  return `https://i.pravatar.cc/150?img=${id}`;
};

// 随机生成手机号
const randomPhone = (): string => {
  const prefixes = ['139', '138', '137', '136', '135', '134', '159', '158', '157', '188', '187', '183'];
  const prefix = randomPick(prefixes);
  const suffix = Array(8).fill(0).map(() => randomNum(0, 9)).join('');
  return `${prefix}${suffix}`;
};

// 随机生成姓名
const randomName = (): string => {
  const firstNames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴', '郑', '孙', '马', '朱', '胡', '林', '何', '高', '梁'];
  const lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞', '平', '刚', '桂英'];
  return randomPick(firstNames) + randomPick(lastNames);
};

// 随机生成邮箱
const randomEmail = (name: string): string => {
  const domains = ['qq.com', '163.com', 'gmail.com', 'outlook.com', 'hotmail.com', 'sina.com', 'sohu.com'];
  const domain = randomPick(domains);
  // 转拼音 - 简单模拟
  const pinyin = name.replace(/[^\x00-\xff]/g, '').toLowerCase() || 'user';
  return `${pinyin}${randomNum(100, 999)}@${domain}`;
};

// 随机生成日期
const randomDate = (start: Date, end: Date): Date => {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
};

// 随机生成日期字符串 (ISO格式)
const randomDateString = (start: Date, end: Date): string => {
  return randomDate(start, end).toISOString();
};

// 随机生成格式化日期字符串
const randomFormattedDate = (start: Date, end: Date, formatStr: string = 'yyyy-MM-dd HH:mm:ss'): string => {
  return format(randomDate(start, end), formatStr);
};

// 随机生成USDT地址
const randomUsdtAddress = (): string => {
  return `0x${Array(40).fill(0).map(() => randomNum(0, 15).toString(16)).join('')}`;
};

// 生成区域代理信息
export const generateAgentInfo = () => {
  const name = randomName();
  return {
    id: generateId('agent_'),
    name: name,
    email: randomEmail(name),
    phone: randomPhone(),
    avatar: randomAvatar(),
    region: randomPick(['华东', '华南', '华北', '华中', '西南', '西北', '东北']),
    commissionRate: randomNum(20, 40),
    joinDate: randomFormattedDate(new Date(2020, 0, 1), new Date(), 'yyyy-MM-dd'),
    status: randomStatus(),
    walletBalance: parseFloat((Math.random() * 10000).toFixed(2))
  };
};

// 生成仪表盘数据
export const generateDashboard = () => {
  const todaySales = parseFloat((Math.random() * 1000).toFixed(2));
  const weekSales = todaySales + parseFloat((Math.random() * 5000).toFixed(2));
  const monthSales = weekSales + parseFloat((Math.random() * 10000).toFixed(2));
  const totalSales = monthSales + parseFloat((Math.random() * 50000).toFixed(2));
  
  const commissionRate = randomNum(20, 40) / 100;
  
  return {
    distributorCount: randomNum(5, 30),
    activeDistributorCount: randomNum(3, 20),
    salesOverview: {
      today: todaySales,
      week: weekSales,
      month: monthSales,
      total: totalSales
    },
    commissionOverview: {
      today: parseFloat((todaySales * commissionRate).toFixed(2)),
      week: parseFloat((weekSales * commissionRate).toFixed(2)),
      month: parseFloat((monthSales * commissionRate).toFixed(2)),
      total: parseFloat((totalSales * commissionRate).toFixed(2)),
      pending: parseFloat((Math.random() * 1000).toFixed(2)),
      available: parseFloat((Math.random() * 2000).toFixed(2))
    },
    pendingWithdrawals: randomNum(0, 10),
    topDistributors: Array(5).fill(null).map(() => {
      const sales = parseFloat((Math.random() * 5000).toFixed(2));
      return {
        id: generateId('dist_'),
        name: randomName(),
        sales: sales,
        commissions: parseFloat((sales * randomNum(5, 15) / 100).toFixed(2))
      };
    }),
    topProducts: Array(5).fill(null).map(() => {
      const sales = randomNum(10, 200);
      const price = parseFloat((Math.random() * 100).toFixed(2));
      return {
        id: randomNum(100, 999),
        name: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派']),
        image: `https://picsum.photos/seed/${randomNum(1, 1000)}/200/200`,
        sales: sales,
        revenue: parseFloat((sales * price).toFixed(2))
      };
    })
  };
};

// 生成经销商列表
export const generateDistributors = (count: number = 15) => {
  return {
    distributors: Array(count).fill(null).map(() => {
      const name = randomName();
      const totalSales = parseFloat((Math.random() * 10000).toFixed(2));
      const monthSales = parseFloat((totalSales * randomNum(10, 30) / 100).toFixed(2));
      const weekSales = parseFloat((monthSales * randomNum(10, 30) / 100).toFixed(2));
      const commissionRate = randomNum(5, 15);
      
      return {
        id: generateId('dist_'),
        name: name,
        email: randomEmail(name),
        phone: randomPhone(),
        avatar: randomAvatar(),
        status: randomStatus(),
        commissionRate: commissionRate,
        sales: {
          total: totalSales,
          month: monthSales,
          week: weekSales
        },
        commissions: {
          total: parseFloat((totalSales * commissionRate / 100).toFixed(2)),
          month: parseFloat((monthSales * commissionRate / 100).toFixed(2)),
          week: parseFloat((weekSales * commissionRate / 100).toFixed(2))
        },
        paymentLinks: {
          total: randomNum(5, 50),
          active: randomNum(1, 20)
        },
        joinedAt: randomDateString(new Date(2023, 0, 1), new Date()),
        lastActiveAt: randomDateString(new Date(2023, 0, 1), new Date())
      };
    }),
    pagination: {
      page: 1,
      limit: count,
      total: 30,
      pages: Math.ceil(30 / count)
    }
  };
};

// 生成经销商详情
export const generateDistributorDetail = (id: string) => {
  const name = randomName();
  const totalSales = parseFloat((Math.random() * 10000).toFixed(2));
  const monthSales = parseFloat((totalSales * randomNum(10, 30) / 100).toFixed(2));
  const weekSales = parseFloat((monthSales * randomNum(10, 30) / 100).toFixed(2));
  const commissionRate = randomNum(5, 15);
  
  const distributorDetail = {
    id: id,
    name: name,
    email: randomEmail(name),
    phone: randomPhone(),
    avatar: randomAvatar(),
    status: randomStatus(),
    commissionRate: commissionRate,
    walletBalance: parseFloat((Math.random() * 2000).toFixed(2)),
    salesOverview: {
      total: totalSales,
      month: monthSales,
      week: weekSales,
      today: parseFloat((weekSales * randomNum(10, 30) / 100).toFixed(2))
    },
    commissionOverview: {
      total: parseFloat((totalSales * commissionRate / 100).toFixed(2)),
      month: parseFloat((monthSales * commissionRate / 100).toFixed(2)),
      week: parseFloat((weekSales * commissionRate / 100).toFixed(2)),
      today: parseFloat((weekSales * randomNum(10, 30) / 100 * commissionRate / 100).toFixed(2)),
      pending: parseFloat((Math.random() * 500).toFixed(2)),
      available: parseFloat((Math.random() * 1000).toFixed(2))
    },
    paymentLinks: {
      total: randomNum(5, 50),
      active: randomNum(1, 20)
    },
    joinedAt: randomDateString(new Date(2023, 0, 1), new Date()),
    lastActiveAt: randomDateString(new Date(2023, 0, 1), new Date()),
    address: {
      province: randomPick(['广东省', '北京市', '上海市', '江苏省', '浙江省']),
      city: randomPick(['广州市', '深圳市', '北京市', '上海市', '南京市', '杭州市']),
      district: randomPick(['海珠区', '天河区', '朝阳区', '浦东新区', '鼓楼区', '西湖区']),
      detail: `${randomNum(1, 999)}号, ${randomNum(1, 100)}单元, ${randomNum(101, 999)}室`
    },
    usdtAddress: randomUsdtAddress(),
    recentOrders: Array(5).fill(null).map(() => {
      const price = parseFloat((Math.random() * 100).toFixed(2));
      const quantity = randomNum(1, 5);
      return {
        id: generateId('order_'),
        productName: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派']),
        price: price,
        quantity: quantity,
        total: parseFloat((price * quantity).toFixed(2)),
        commission: parseFloat((price * quantity * commissionRate / 100).toFixed(2)),
        createdAt: randomDateString(new Date(2023, 0, 1), new Date()),
        status: randomOrderStatus()
      };
    }),
    recentWithdrawals: Array(3).fill(null).map(() => {
      const status = randomWithdrawalStatus();
      const createdAt = randomDate(new Date(2023, 0, 1), new Date());
      let completedAt = null;
      if (['approved', 'completed'].includes(status)) {
        completedAt = new Date(createdAt.getTime() + randomNum(1, 7) * 24 * 60 * 60 * 1000);
      }
      
      return {
        id: generateId('wdr_'),
        amount: parseFloat((Math.random() * 1000).toFixed(2)),
        status: status,
        createdAt: createdAt.toISOString(),
        completedAt: completedAt ? completedAt.toISOString() : null
      };
    })
  };
  
  return distributorDetail;
};

// 生成订单列表
export const generateOrders = (count: number = 20) => {
  return {
    orders: Array(count).fill(null).map(() => {
      const price = parseFloat((Math.random() * 100).toFixed(2));
      const quantity = randomNum(1, 5);
      const total = parseFloat((price * quantity).toFixed(2));
      const commissionRate = randomNum(5, 15);
      const name = randomName();
      
      return {
        id: generateId('order_'),
        distributorId: generateId('dist_'),
        distributorName: name,
        productName: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派']),
        productImage: `https://picsum.photos/seed/${randomNum(1, 1000)}/200/200`,
        price: price,
        quantity: quantity,
        total: total,
        commission: parseFloat((total * commissionRate / 100).toFixed(2)),
        commissionRate: commissionRate,
        paymentMethod: randomPick(['PayPal', 'USDT', '微信支付', '支付宝']),
        createdAt: randomDateString(new Date(2023, 0, 1), new Date()),
        status: randomOrderStatus(),
        customer: {
          name: randomName(),
          phone: randomPhone(),
          address: `${randomPick(['广东省', '北京市', '上海市', '江苏省', '浙江省'])}${randomPick(['广州市', '深圳市', '北京市', '上海市', '南京市', '杭州市'])}${randomPick(['海珠区', '天河区', '朝阳区', '浦东新区', '鼓楼区', '西湖区'])}${randomNum(1, 999)}号`
        }
      };
    }),
    pagination: {
      page: 1,
      limit: count,
      total: 100,
      pages: Math.ceil(100 / count)
    }
  };
};

// 生成提现列表
export const generateWithdrawals = (count: number = 10) => {
  return {
    withdrawals: Array(count).fill(null).map(() => {
      const status = randomWithdrawalStatus();
      const createdAt = randomDate(new Date(2023, 0, 1), new Date());
      let completedAt = null;
      if (['approved', 'completed'].includes(status)) {
        completedAt = new Date(createdAt.getTime() + randomNum(1, 7) * 24 * 60 * 60 * 1000);
      }
      
      return {
        id: generateId('wdr_'),
        amount: parseFloat((Math.random() * 1000).toFixed(2)),
        status: status,
        usdtAddress: randomUsdtAddress(),
        createdAt: createdAt.toISOString(),
        completedAt: completedAt ? completedAt.toISOString() : null,
        remarks: status === 'rejected' ? '地址无效或资金不足' : null,
        timeline: [
          {
            status: 'pending',
            timestamp: createdAt.toISOString(),
            description: '提现申请已提交'
          },
          ...(['approved', 'rejected', 'completed'].includes(status) ?
            [{
              status: status === 'rejected' ? 'rejected' : 'approved',
              timestamp: new Date(createdAt.getTime() + randomNum(1, 3) * 24 * 60 * 60 * 1000).toISOString(),
              description: status === 'rejected' ? '提现申请被拒绝' : '提现申请已批准'
            }] : []),
          ...(status === 'completed' && completedAt ?
            [{
              status: 'completed',
              timestamp: completedAt.toISOString(),
              description: '提现已完成，资金已转入USDT地址'
            }] : [])
        ]
      };
    }),
    pagination: {
      page: 1,
      limit: count,
      total: 30,
      pages: Math.ceil(30 / count)
    }
  };
};

// 生成经销商提现列表
export const generateDistributorWithdrawals = (count: number = 10) => {
  return {
    withdrawals: Array(count).fill(null).map(() => {
      const status = randomWithdrawalStatus();
      const createdAt = randomDate(new Date(2023, 0, 1), new Date());
      let completedAt = null;
      if (['approved', 'completed'].includes(status)) {
        completedAt = new Date(createdAt.getTime() + randomNum(1, 7) * 24 * 60 * 60 * 1000);
      }
      
      const name = randomName();
      
      return {
        id: generateId('wdr_'),
        distributorId: generateId('dist_'),
        distributorName: name,
        amount: parseFloat((Math.random() * 1000).toFixed(2)),
        status: status,
        usdtAddress: randomUsdtAddress(),
        createdAt: createdAt.toISOString(),
        completedAt: completedAt ? completedAt.toISOString() : null,
        remarks: status === 'rejected' ? '地址无效或资金不足' : null,
        timeline: [
          {
            status: 'pending',
            timestamp: createdAt.toISOString(),
            description: '提现申请已提交'
          },
          ...(['approved', 'rejected', 'completed'].includes(status) ?
            [{
              status: status === 'rejected' ? 'rejected' : 'approved',
              timestamp: new Date(createdAt.getTime() + randomNum(1, 3) * 24 * 60 * 60 * 1000).toISOString(),
              description: status === 'rejected' ? '提现申请被拒绝' : '提现申请已批准'
            }] : []),
          ...(status === 'completed' && completedAt ?
            [{
              status: 'completed',
              timestamp: completedAt.toISOString(),
              description: '提现已完成，资金已转入USDT地址'
            }] : [])
        ]
      };
    }),
    pagination: {
      page: 1,
      limit: count,
      total: 30,
      pages: Math.ceil(30 / count)
    }
  };
};

// 生成统计数据
export const generateStatistics = (params: {period?: string} = {}) => {
  // 根据参数决定统计周期
  const period = params.period || 'month';
  
  let labels: string[] = [];
  let salesData: number[] = [];
  let commissionsData: number[] = [];
  
  switch(period) {
    case 'week':
      labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      break;
    case 'month':
      labels = Array(30).fill(0).map((_, i) => `${i + 1}日`);
      break;
    case 'year':
      labels = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      break;
    default:
      labels = Array(30).fill(0).map((_, i) => `${i + 1}日`);
  }
  
  // 生成模拟销售数据和佣金数据
  for (let i = 0; i < labels.length; i++) {
    const sales = parseFloat((Math.random() * 1000).toFixed(2));
    salesData.push(sales);
    commissionsData.push(parseFloat((sales * randomNum(20, 40) / 100).toFixed(2)));
  }
  
  return {
    salesTrend: {
      labels,
      series: [
        {
          name: '销售额',
          data: salesData
        }
      ]
    },
    commissionsTrend: {
      labels,
      series: [
        {
          name: '佣金',
          data: commissionsData
        }
      ]
    },
    distributorPerformance: Array(10).fill(null).map(() => {
      const name = randomName();
      const sales = parseFloat((Math.random() * 10000).toFixed(2));
      const commissionRate = randomNum(5, 15);
      
      return {
        id: generateId('dist_'),
        name: name,
        avatar: randomAvatar(),
        sales: sales,
        commission: parseFloat((sales * commissionRate / 100).toFixed(2)),
        commissionRate: commissionRate,
        orderCount: randomNum(10, 100)
      };
    }),
    productPerformance: Array(10).fill(null).map(() => {
      const sales = randomNum(10, 200);
      const price = parseFloat((Math.random() * 100).toFixed(2));
      
      return {
        id: randomNum(100, 999),
        name: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派']),
        image: `https://picsum.photos/seed/${randomNum(1, 1000)}/200/200`,
        sales: sales,
        revenue: parseFloat((sales * price).toFixed(2)),
        commission: parseFloat((sales * price * randomNum(5, 15) / 100).toFixed(2))
      };
    })
  };
};

// 生成控制台概览数据
export const generateDashboardOverviewData = () => {
  const totalSales = parseFloat((Math.random() * 10000000).toFixed(2));
  const todaySales = parseFloat((totalSales * randomNum(1, 5) / 100).toFixed(2)); // 今日业绩约为总销售额的1-5%
  const totalOrders = randomNum(5000, 20000);
  const distributorsCount = randomNum(50, 200);
  const customersCount = randomNum(2000, 10000);
  const totalCommission = parseFloat((totalSales * randomNum(20, 40) / 100).toFixed(2));
  const pendingCommission = parseFloat((totalCommission * randomNum(10, 30) / 100).toFixed(2));
  
  return {
    totalSales: totalSales,
    todaySales: todaySales, // 添加今日业绩
    totalOrders: totalOrders,
    distributorsCount: distributorsCount,
    customersCount: customersCount,
    totalCommission: totalCommission,
    pendingCommission: pendingCommission,
    growthRates: {
      salesGrowth: randomNum(-5, 30),
      todaySalesGrowth: randomNum(0, 40), // 添加今日业绩增长率
      ordersGrowth: randomNum(-5, 25),
      distributorsGrowth: randomNum(0, 20),
      customersGrowth: randomNum(5, 40),
      commissionGrowth: randomNum(-10, 35),
      pendingCommissionGrowth: randomNum(-5, 25) // 添加分销商佣金增长率
    }
  };
};

// 生成销售趋势数据
export const generateSalesTrendData = (days: number = 30) => {
  const result = [];
  const today = new Date();
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(today.getDate() - i);
    
    const sales = parseFloat((Math.random() * 100000 + 50000).toFixed(2));
    const orders = randomNum(100, 500);
    const commission = parseFloat((sales * randomNum(20, 40) / 100).toFixed(2));
    
    result.push({
      date: format(date, 'yyyy-MM-dd'),
      sales: sales,
      orders: orders,
      commission: commission
    });
  }
  
  return result;
};

// 生成分销商数据列表，直接返回分销商数组
export const generateDistributorsData = (count: number = 15) => {
  return Array(count).fill(null).map(() => {
    const name = randomName();
    const totalSales = parseFloat((Math.random() * 100000 + 10000).toFixed(2));
    const totalOrders = randomNum(50, 500);
    const commissionRate = randomNum(5, 15);
    const totalCommission = parseFloat((totalSales * commissionRate / 100).toFixed(2));
    const joinDate = randomFormattedDate(new Date(2021, 0, 1), new Date(2023, 11, 31), 'yyyy-MM-dd');
    
    // 随机选择状态，确保数据多样化
    const status = randomPick(['active', 'inactive', 'pending']);
    
    return {
      id: generateId('dist_'),
      name,
      avatar: randomAvatar(),
      commissionRate,
      totalSales,
      totalOrders,
      totalCommission,
      joinDate,
      status
    };
  });
};

// 模拟API响应格式
export const mockResponse = (data: any) => {
  return {
    code: 200,
    message: 'Success',
    data
  };
};

// 生成分销商详情数据
export const generateDistributorDetailData = (id: string) => {
  // 生成基本信息
  const name = randomName();
  const joinDate = randomFormattedDate(new Date(2020, 0, 1), new Date(), 'yyyy-MM-dd');
  const commissionRate = randomNum(5, 30);
  const totalSales = parseFloat((Math.random() * 100000).toFixed(2));
  const totalOrders = randomNum(50, 500);
  const totalCommission = parseFloat((totalSales * commissionRate / 100).toFixed(2));
  
  const levelMap: Record<number, 'standard' | 'premium' | 'vip'> = {
    1: 'standard',
    2: 'premium',
    3: 'vip'
  };
  
  const level = levelMap[randomNum(1, 3)] as 'standard' | 'premium' | 'vip';
  const status = randomPick(['active', 'inactive', 'pending']) as 'active' | 'inactive' | 'pending';
  
  // 返回详情数据
  return {
    id: id || generateId('DS', 4),
    name: `${name}分销商`,
    avatar: randomAvatar(),
    contactPerson: name,
    phone: randomPhone(),
    email: randomEmail(name),
    address: `${randomPick(['广东省', '北京市', '上海市', '江苏省', '浙江省'])}${randomPick(['广州市', '深圳市', '北京市', '上海市', '南京市', '杭州市'])}${randomPick(['天河区', '朝阳区', '浦东新区', '鼓楼区', '西湖区'])}`,
    commissionRate,
    totalSales,
    totalOrders,
    totalCommission,
    joinDate,
    level,
    status,
    remarks: Math.random() > 0.5 ? `这是${name}分销商的备注信息，添加于${randomFormattedDate(new Date(2023, 0, 1), new Date(), 'yyyy-MM-dd')}` : '',
  };
};

/**
 * 生成分销商销售数据
 * @param id 分销商ID
 * @param days 天数，默认30天
 * @returns 销售数据数组
 */
export const generateDistributorSalesData = (id: string, days: number = 30) => {
  // 为了同一个ID生成固定的随机数据
  const idSeed = parseInt(id.replace(/\D/g, ''), 10) || 1;
  
  // 基础销售额（根据ID稍微变化，避免所有分销商数据一样）
  const baseSales = 1000 + (idSeed % 10) * 500;
  
  // 销售趋势因子（决定整体上升或下降趋势）
  const trendFactor = (idSeed % 5 - 2) * 0.02; // -0.04 到 0.04 之间
  
  // 基础订单量
  const baseOrders = 10 + (idSeed % 5) * 3;
  
  // 订单趋势因子
  const orderTrendFactor = (idSeed % 5 - 2) * 0.015;
  
  // 佣金率 (5% - 15%)
  const commissionRate = 0.05 + (idSeed % 10) * 0.01;
  
  // 当前日期
  const today = new Date();
  
  // 生成每天的销售数据
  const salesData = [];
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    const formattedDate = format(date, 'yyyy-MM-dd');
    
    // 考虑周末销售额提高
    const isWeekend = date.getDay() === 0 || date.getDay() === 6;
    const weekendFactor = isWeekend ? 1.4 : 1;
    
    // 日期影响（月初和月中可能有促销活动）
    const dayOfMonth = date.getDate();
    const promotionFactor = (dayOfMonth <= 3 || (dayOfMonth >= 15 && dayOfMonth <= 17)) ? 1.3 : 1;
    
    // 计算当天的销售额，考虑趋势、周末因素、促销因素和随机波动
    const trendValue = baseSales * (1 + trendFactor * i);
    const daySales = trendValue * weekendFactor * promotionFactor * (0.8 + Math.random() * 0.4);
    
    // 计算订单数量，同样考虑趋势和随机波动
    const orderTrendValue = baseOrders * (1 + orderTrendFactor * i);
    const dayOrders = Math.max(1, Math.round(orderTrendValue * weekendFactor * (0.8 + Math.random() * 0.4)));
    
    // 计算佣金
    const dayCommission = daySales * commissionRate;
    
    salesData.push({
      date: formattedDate,
      sales: parseFloat(daySales.toFixed(2)),
      orders: dayOrders,
      commission: parseFloat(dayCommission.toFixed(2))
    });
  }
  
  return salesData;
};

/**
 * 生成分销商订单数据
 * @param distributorId 分销商ID
 * @param count 订单数量
 * @returns 订单数据数组
 */
export const generateDistributorOrdersData = (distributorId: string, count: number = 20) => {
  // 为了保证同一个ID生成相同的随机数据
  const idSeed = parseInt(distributorId.replace(/\D/g, ''), 10) || 1;
  
  // 订单状态选项
  const orderStatuses = ['pending', 'processing', 'completed', 'cancelled'];
  
  // 商品名称选项
  const productNames = [
    '香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', 
    '可乐', '奶茶', '冰淇淋', '苹果派', '麦香咖啡', '鸡翅', 
    '汉堡包', '麦旋风', '鸡肉卷', '牛肉卷', '早餐套餐', '鸡米花'
  ];
  
  // 当前时间
  const now = new Date();
  
  // 生成订单
  const orders = [];
  
  for (let i = 0; i < count; i++) {
    // 使用distributorId和索引生成唯一订单ID
    const orderId = `ODR${distributorId.slice(-4)}-${(1000 + i + idSeed % 100).toString().slice(1)}`;
    
    // 订单商品数量 (1-4个商品)
    const productCount = Math.max(1, Math.floor(Math.random() * 4) + 1);
    
    // 生成随机商品
    const products = [];
    let totalAmount = 0;
    
    for (let j = 0; j < productCount; j++) {
      const productName = productNames[Math.floor(Math.random() * productNames.length)];
      const quantity = Math.floor(Math.random() * 3) + 1; // 1-3份
      const price = parseFloat((Math.random() * 30 + 10).toFixed(2)); // 10-40元
      const productAmount = quantity * price;
      
      totalAmount += productAmount;
      
      products.push({
        name: productName,
        quantity: quantity,
        price: price,
        amount: parseFloat(productAmount.toFixed(2))
      });
    }
    
    // 计算佣金（订单金额的5%-15%）
    const commissionRate = (5 + Math.floor(Math.random() * 10)) / 100;
    const commission = parseFloat((totalAmount * commissionRate).toFixed(2));
    
    // 订单状态
    const status = orderStatuses[Math.floor(Math.random() * orderStatuses.length)];
    
    // 订单创建时间（过去60天内的随机时间）
    const orderDate = new Date(now);
    orderDate.setDate(now.getDate() - Math.floor(Math.random() * 60));
    
    // 订单时间格式化
    const orderTime = format(orderDate, 'yyyy-MM-dd HH:mm:ss');
    
    orders.push({
      id: orderId,
      distributorId: distributorId,
      orderTime: orderTime,
      products: products,
      totalAmount: parseFloat(totalAmount.toFixed(2)),
      commission: commission,
      status: status,
      customerName: randomName(),
      customerPhone: randomPhone(),
      paymentMethod: 'PayPal',
      deliveryAddress: `${randomName()}的地址，随机城市，随机区域，电话：${randomPhone()}`
    });
  }
  
  return orders;
};

/**
 * 生成佣金记录数据
 * @param count 佣金记录数量
 * @returns 佣金记录数组
 */
export const generateCommissionData = (count: number = 15) => {
  // 佣金类型
  const commissionTypes = ['orderCommission', 'referralCommission', 'promotionCommission', 'specialCommission'];
  
  // 佣金状态
  const commissionStatuses = ['pending', 'available', 'settled'];
  
  // 生成佣金记录
  const commissions = [];
  
  for (let i = 0; i < count; i++) {
    // 随机选择佣金类型和状态
    const type = randomPick(commissionTypes);
    const status = randomPick(commissionStatuses);
    
    // 随机生成佣金金额 (10-1000元)
    const amount = parseFloat((Math.random() * 990 + 10).toFixed(2));
    
    // 佣金产生时间 (过去1年内)
    const commissionTime = randomDate(new Date(new Date().setFullYear(new Date().getFullYear() - 1)), new Date());
    
    // 分销商信息
    const distributorName = randomName();
    const distributor = {
      id: generateId('dist_'),
      name: `${distributorName}分销商`,
      avatar: randomAvatar(),
    };
    
    // 订单信息
    const orderTotal = parseFloat((Math.random() * 2000 + 100).toFixed(2));
    const order = {
      id: generateId('order_'),
      total: orderTotal,
      time: format(randomDate(new Date(commissionTime.getTime() - 24 * 60 * 60 * 1000), commissionTime), 'yyyy-MM-dd HH:mm:ss'),
      productName: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派']),
    };
    
    // 结算时间 (只有已结算的佣金才有结算时间)
    let settleTime = null;
    if (status === 'settled') {
      settleTime = format(randomDate(commissionTime, new Date()), 'yyyy-MM-dd HH:mm:ss');
    }
    
    commissions.push({
      id: generateId('comm_'),
      time: format(commissionTime, 'yyyy-MM-dd HH:mm:ss'),
      distributor,
      order,
      amount,
      type,
      status,
      settleTime,
      remarks: Math.random() > 0.7 ? `这是佣金ID为${generateId('comm_')}的备注信息` : ''
    });
  }
  
  // 按时间降序排序，最新的佣金记录排在前面
  commissions.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
  
  return commissions;
};

/**
 * 生成佣金概览数据
 * @returns 佣金概览数据
 */
export const generateCommissionOverview = () => {
  // 生成基础金额
  const totalCommission = parseFloat((Math.random() * 50000 + 10000).toFixed(2));
  const availableCommission = parseFloat((totalCommission * 0.3).toFixed(2));
  const pendingCommission = parseFloat((totalCommission * 0.2).toFixed(2));
  const settledCommission = parseFloat((totalCommission * 0.5).toFixed(2));
  const currentMonthCommission = parseFloat((totalCommission * 0.15).toFixed(2));

  return {
    totalCommission,
    availableCommission,
    pendingCommission,
    settledCommission,
    currentMonthCommission
  };
};

/**
 * 生成佣金趋势数据
 * @param months 月份数量
 * @returns 月度佣金趋势数据
 */
export const generateCommissionTrend = (months: number = 6) => {
  const endDate = new Date();
  const result = [];

  // 基础佣金金额 (1000-3000)
  const baseCommission = Math.random() * 2000 + 1000;
  
  // 季节因子，模拟季节性趋势
  const seasonalFactor = (month: number) => {
    // 简单的正弦波模拟季节性变化
    return 0.2 * Math.sin((month / 12) * 2 * Math.PI) + 1;
  };

  // 增长因子 (0.02-0.08)
  const growthFactor = Math.random() * 0.06 + 0.02;

  for (let i = months - 1; i >= 0; i--) {
    const date = new Date(endDate);
    date.setMonth(endDate.getMonth() - i);
    
    // 当前月份从0开始(0-11)
    const currentMonth = date.getMonth();
    
    // 计算佣金值，考虑基础金额、季节因素、增长趋势和随机波动
    const seasonal = seasonalFactor(currentMonth);
    const growth = 1 + growthFactor * (months - i - 1);
    const random = 0.8 + Math.random() * 0.4; // 随机波动 (0.8-1.2)
    
    const commission = baseCommission * seasonal * growth * random;
    
    result.push({
      month: format(date, 'yyyy-MM'),
      commission: parseFloat(commission.toFixed(2))
    });
  }

  return result;
};

/**
 * 生成佣金构成数据
 * @returns 佣金类型占比数据
 */
export const generateCommissionComposition = () => {
  // 确保百分比总和为100%
  let orderPercent = randomNum(40, 60);
  let referralPercent = randomNum(15, 25);
  let promotionPercent = randomNum(10, 20);
  let specialPercent = 100 - (orderPercent + referralPercent + promotionPercent);
  
  // 根据百分比计算金额
  const totalAmount = randomNum(10000, 50000);
  
  return [
    {
      type: 'orderCommission',
      name: '订单佣金',
      percent: orderPercent,
      amount: parseFloat(((orderPercent / 100) * totalAmount).toFixed(2))
    },
    {
      type: 'referralCommission',
      name: '推荐佣金',
      percent: referralPercent,
      amount: parseFloat(((referralPercent / 100) * totalAmount).toFixed(2))
    },
    {
      type: 'promotionCommission',
      name: '促销佣金',
      percent: promotionPercent,
      amount: parseFloat(((promotionPercent / 100) * totalAmount).toFixed(2))
    },
    {
      type: 'specialCommission',
      name: '特殊佣金',
      percent: specialPercent,
      amount: parseFloat(((specialPercent / 100) * totalAmount).toFixed(2))
    }
  ];
};

/**
 * 生成分销商佣金排行榜数据
 * @param count 记录数量
 * @returns 分销商佣金排行数据
 */
export const generateDistributorCommissionRanking = (count: number = 10) => {
  const result = [];
  
  for (let i = 0; i < count; i++) {
    const name = randomName();
    // 佣金金额递减，保证排序效果
    const commissionBase = 10000 - (i * 800);
    const commission = parseFloat((commissionBase * (0.9 + Math.random() * 0.2)).toFixed(2));
    const orderCount = randomNum(20, 100);

    result.push({
      id: generateId('dist_'),
      name: `${name}分销商`,
      avatar: randomAvatar(),
      commission,
      orderCount,
      commissionRate: randomNum(5, 15)
    });
  }
  
  return result;
};

/**
 * 生成区域代理提现记录数据
 * @param params 筛选参数（开始日期、结束日期、状态）
 * @returns 提现记录数据数组
 */
export const generateWithdrawalRecordsData = (params: { 
  startDate?: string; 
  endDate?: string; 
  status?: string;
  count?: number;
} = {}) => {
  // 确定生成数量
  const count = params.count || 20;
  
  // 定义状态列表
  const statuses = ['pending', 'processing', 'completed', 'rejected'];
  
  // 定义拒绝原因
  const rejectReasons = [
    'USDT地址格式不正确',
    '提现金额超出可提现余额',
    '账户存在风险，需联系管理员',
    '提现金额未达到最低要求',
    '系统维护中，暂时无法提现'
  ];
  
  // 生成记录
  const records = [];
  
  for (let i = 0; i < count; i++) {
    // 随机金额（100-5000之间）
    const amount = parseFloat((Math.random() * 4900 + 100).toFixed(2));
    
    // 随机状态
    const status = randomPick(statuses);
    
    // 申请日期（过去一年内）
    const now = new Date();
    const oneYearAgo = new Date();
    oneYearAgo.setFullYear(now.getFullYear() - 1);
    const applicationDate = randomDate(oneYearAgo, now);
    
    // 处理日期（申请后1-3天）
    let processedDate = null;
    if (status !== 'pending') {
      processedDate = new Date(applicationDate);
      processedDate.setDate(applicationDate.getDate() + randomNum(1, 3));
    }
    
    // 完成日期（处理后1-2天）
    let completedDate = null;
    if (status === 'completed' && processedDate) {
      completedDate = new Date(processedDate);
      completedDate.setDate(processedDate.getDate() + randomNum(1, 2));
    }
    
    // 生成记录
    records.push({
      id: generateId('wtd_', 8),
      amount,
      status,
      applicationDate: applicationDate.toISOString(),
      processedDate: processedDate ? processedDate.toISOString() : null,
      completedDate: completedDate ? completedDate.toISOString() : null,
      usdtAddress: randomUsdtAddress(),
      rejectReason: status === 'rejected' ? randomPick(rejectReasons) : null,
      fee: status === 'completed' ? parseFloat((amount * 0.01).toFixed(2)) : null,
      actualAmount: status === 'completed' ? parseFloat((amount * 0.99).toFixed(2)) : null,
      timeline: [
        {
          status: 'pending',
          time: applicationDate.toISOString(),
          description: '提现申请已提交'
        },
        ...(processedDate ? [{
          status: status === 'rejected' ? 'rejected' : 'processing',
          time: processedDate.toISOString(),
          description: status === 'rejected' ? '提现申请被拒绝' : '提现申请处理中'
        }] : []),
        ...(completedDate ? [{
          status: 'completed',
          time: completedDate.toISOString(),
          description: '提现已完成，资金已转入USDT地址'
        }] : [])
      ]
    });
  }
  
  // 筛选数据
  let filteredRecords = [...records];
  
  // 按日期筛选
  if (params.startDate) {
    const startDate = new Date(params.startDate);
    filteredRecords = filteredRecords.filter(
      record => new Date(record.applicationDate) >= startDate
    );
  }
  
  if (params.endDate) {
    const endDate = new Date(params.endDate);
    endDate.setHours(23, 59, 59, 999); // 设置为当天的最后一毫秒
    filteredRecords = filteredRecords.filter(
      record => new Date(record.applicationDate) <= endDate
    );
  }
  
  // 按状态筛选
  if (params.status) {
    filteredRecords = filteredRecords.filter(
      record => record.status === params.status
    );
  }
  
  // 按申请日期排序（降序）
  return filteredRecords.sort(
    (a, b) => new Date(b.applicationDate).getTime() - new Date(a.applicationDate).getTime()
  );
};

/**
 * 生成佣金规则数据
 * @returns 佣金规则数据对象
 */
export const generateCommissionRulesData = () => {
  return {
    // 基础佣金比例规则
    baseRates: {
      min: 20,
      max: 40,
      levels: [
        {
          level: 'junior',
          name: '初级代理',
          range: '20% - 25%',
          condition: '初始等级'
        },
        {
          level: 'intermediate',
          name: '中级代理',
          range: '25% - 35%',
          condition: '月销售额 ≥ 10万元'
        },
        {
          level: 'senior',
          name: '高级代理',
          range: '35% - 40%',
          condition: '月销售额 ≥ 30万元'
        }
      ]
    },

    // 分销商佣金设置规则
    distributorRates: {
      min: 5,
      max: 15,
      maxRatio: 0.5, // 最高为代理佣金的50%
      specialProducts: {
        discount: 0.8, // 特惠产品佣金比例下调20%
        premium: 1.5 // 高端产品佣金比例上调50%
      },
      adjustmentCycle: 'monthly' // 每月调整
    },

    // 佣金计算方式
    calculationMethods: [
      {
        type: 'orderCommission',
        name: '订单佣金',
        formula: '订单金额 × 区域代理佣金比例',
        example: '订单金额¥100，代理佣金比例30%，则佣金为¥30'
      },
      {
        type: 'referralCommission',
        name: '推荐佣金',
        formula: '新分销商首月销售额 × 5%',
        example: '新分销商首月销售¥2000，则推荐佣金为¥100'
      },
      {
        type: 'promotionCommission',
        name: '促销佣金',
        formula: '促销活动总销售额 × 促销佣金比例',
        example: '促销佣金比例由平台在活动期间指定'
      }
    ],

    // 佣金结算周期
    settlementCycle: {
      waitingPeriod: 7, // T+7天
      withdrawalProcessing: 3, // 提现处理3个工作日
      autoSettlementDay: 10 // 每月10日自动结算
    },

    // 提现规则
    withdrawalRules: {
      minAmount: 100, // 最低提现金额
      fee: 0.01, // 手续费比例1%
      minFee: 1, // 最低手续费1元
      maxFee: 50, // 最高手续费50元
      dailyLimit: 50000, // 单日提现上限
      methods: ['USDT'], // 支持的提现方式
      processingHours: '09:00-18:00', // 处理时间
      fastestProcessing: 3 // 最快3小时
    },

    // 常见问题
    faqs: [
      {
        question: '佣金比例如何提升？',
        answer: '提高销售业绩是提升佣金比例的主要方式。当月销售额达到指定标准后，系统将自动评估并可能提升您的佣金比例。您也可以联系平台客服申请评估提升佣金比例。'
      },
      {
        question: '订单退款后佣金如何处理？',
        answer: '如果订单在佣金结算前退款，则相应佣金将不予结算。如果订单在佣金已结算后退款，则会从下次待结算佣金中扣除相应金额。如待结算佣金不足，则会从可提现佣金中扣除。'
      },
      {
        question: '为什么我的分销商佣金比例设置被限制？',
        answer: '分销商佣金比例不能超过区域代理自身佣金比例的50%，这是为了确保合理的利润分配和激励结构。如您需要为特定分销商设置更高佣金，请联系平台客服申请特殊审批。'
      },
      {
        question: '如何查看佣金明细和提现记录？',
        answer: '您可以在佣金管理模块的"佣金记录"页面查看所有佣金明细，在"提现管理"页面查看所有提现记录。系统保留最近12个月的完整记录，更早的记录可联系客服获取。'
      },
      {
        question: '我可以将佣金转给其他代理或分销商吗？',
        answer: '目前系统不支持佣金直接转账给其他代理或分销商。您需要先提现到自己的USDT钱包，然后通过其他方式转账。我们计划在未来版本中添加内部转账功能。'
      }
    ]
  };
};

/**
 * 生成销售分析数据
 * @param params 可选参数（时间范围、筛选条件等）
 * @returns 销售分析数据
 */
export const generateSalesAnalyticsData = (params: {
  period?: 'day' | 'week' | 'month';
  startDate?: string;
  endDate?: string;
} = {}) => {
  // 默认参数
  const period = params.period || 'day';
  
  // 销售概览数据
  const salesOverview = {
    totalSales: parseFloat((Math.random() * 1000000 + 500000).toFixed(2)),
    totalOrders: randomNum(2000, 8000),
    averageOrderValue: parseFloat((Math.random() * 200 + 100).toFixed(2)),
    conversionRate: parseFloat((Math.random() * 10 + 2).toFixed(2)),
    activeDistributors: randomNum(30, 100),
    growthRates: {
      salesGrowth: parseFloat((Math.random() * 30 - 5).toFixed(1)),
      ordersGrowth: parseFloat((Math.random() * 25 - 3).toFixed(1)),
      aovGrowth: parseFloat((Math.random() * 15 - 5).toFixed(1)),
      conversionGrowth: parseFloat((Math.random() * 12 - 2).toFixed(1)),
      distributorsGrowth: parseFloat((Math.random() * 20 - 2).toFixed(1))
    }
  };
  
  // 销售趋势数据
  let trendLabels: string[] = [];
  let salesData: number[] = [];
  let ordersData: number[] = [];
  
  // 根据周期生成不同的标签和数据点数量
  switch(period) {
    case 'day':
      // 按小时生成数据（24小时）
      trendLabels = Array(24).fill(0).map((_, i) => `${i}:00`);
      break;
    case 'week':
      // 最近7天
      trendLabels = Array(7).fill(0).map((_, i) => {
        const date = new Date();
        date.setDate(date.getDate() - (6 - i));
        return format(date, 'MM-dd');
      });
      break;
    case 'month':
      // 最近30天
      trendLabels = Array(30).fill(0).map((_, i) => {
        const date = new Date();
        date.setDate(date.getDate() - (29 - i));
        return format(date, 'MM-dd');
      });
      break;
  }
  
  // 生成销售和订单数据
  // 基础值（确保趋势合理）
  const baseSales = 10000 + Math.random() * 5000;
  const baseOrders = 50 + Math.random() * 30;
  
  // 随机增长率（-2%到5%之间的日增长）
  const growthRate = Math.random() * 0.07 - 0.02;
  
  // 生成每个时间点的数据
  for (let i = 0; i < trendLabels.length; i++) {
    // 计算当前值（考虑累积增长）
    const currentSales = baseSales * Math.pow(1 + growthRate, i) * (0.8 + Math.random() * 0.4);
    const currentOrders = baseOrders * Math.pow(1 + growthRate, i) * (0.8 + Math.random() * 0.4);
    
    // 添加到数据数组
    salesData.push(parseFloat(currentSales.toFixed(2)));
    ordersData.push(Math.round(currentOrders));
  }
  
  // 销售分布数据
  const salesDistribution = {
    // 按产品类别分布
    byCategory: [
      { name: '主食类', value: randomNum(30, 45), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '小吃类', value: randomNum(15, 25), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '饮料类', value: randomNum(10, 20), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '甜点类', value: randomNum(5, 15), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '套餐类', value: randomNum(10, 20), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) }
    ],
    
    // 按地区分布
    byRegion: [
      { name: '华东', value: randomNum(25, 35), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '华南', value: randomNum(15, 25), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '华北', value: randomNum(15, 25), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '华中', value: randomNum(10, 15), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '西南', value: randomNum(5, 15), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '西北', value: randomNum(3, 10), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '东北', value: randomNum(3, 10), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) }
    ],
    
    // 按渠道分布
    byChannel: [
      { name: '线上自营', value: randomNum(40, 60), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '线下门店', value: randomNum(20, 30), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '第三方平台', value: randomNum(10, 20), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) },
      { name: '批发渠道', value: randomNum(5, 15), growth: parseFloat((Math.random() * 20 - 5).toFixed(1)) }
    ]
  };
  
  // 热门产品数据
  const popularProducts = Array(10).fill(null).map((_, i) => {
    const sales = randomNum(50, 500);
    const price = parseFloat((Math.random() * 100 + 20).toFixed(2));
    const revenue = parseFloat((sales * price).toFixed(2));
    const growth = parseFloat((Math.random() * 40 - 10).toFixed(1));
    
    return {
      id: randomNum(1000, 9999),
      rank: i + 1,
      name: randomPick(['香辣鸡腿堡', '巨无霸', '麦辣鸡翅', '麦香鱼', '麦乐鸡', '薯条', '可乐', '奶茶', '冰淇淋', '苹果派', '麦香咖啡', '鸡翅', '汉堡包', '麦旋风', '鸡肉卷', '牛肉卷', '早餐套餐', '鸡米花']),
      image: `https://picsum.photos/seed/${randomNum(1, 1000)}/200/200`,
      sales,
      price,
      revenue,
      growth
    };
  });
  
  // 转化漏斗数据
  const conversionFunnel: ConversionFunnelItem[] = [
    { stage: '浏览商品', count: randomNum(10000, 20000) },
    { stage: '加入购物车', count: randomNum(5000, 8000) },
    { stage: '开始结账', count: randomNum(3000, 4500) },
    { stage: '支付订单', count: randomNum(2000, 3000) },
    { stage: '完成订单', count: randomNum(1800, 2800) }
  ];
  
  // 计算转化率
  for (let i = 1; i < conversionFunnel.length; i++) {
    const conversionRate = parseFloat((conversionFunnel[i].count / conversionFunnel[i-1].count * 100).toFixed(2));
    conversionFunnel[i].conversionRate = conversionRate;
  }
  
  // 分销商销售排行数据
  const topDistributors = Array(10).fill(null).map((_, i) => {
    const name = randomName();
    const sales = parseFloat((Math.random() * 500000 + 100000).toFixed(2));
    const orders = randomNum(100, 1000);
    const growth = parseFloat((Math.random() * 40 - 10).toFixed(1));
    
    return {
      id: generateId('dist_'),
      rank: i + 1,
      name: `${name}分销商`,
      avatar: randomAvatar(),
      sales,
      orders,
      growth
    };
  });
  
  // 按销售额降序排序
  popularProducts.sort((a, b) => b.sales - a.sales);
  topDistributors.sort((a, b) => b.sales - a.sales);
  
  return {
    overview: salesOverview,
    trend: {
      labels: trendLabels,
      sales: salesData,
      orders: ordersData
    },
    distribution: salesDistribution,
    popularProducts,
    conversionFunnel,
    topDistributors
  };
};

/**
 * 生成分销商业绩分析数据
 * @param options 参数选项
 */
export const generateDistributorAnalyticsData = (options: {
  level?: string;
  startDate?: string;
  endDate?: string;
  period?: 'day' | 'week' | 'month';
} = {}) => {
  const { level, period = 'day' } = options;
  
  // 核心指标数据
  const overview = {
    activeDistributors: randomNum(200, 600),
    activeDistributorsGrowth: randomPercentage(-15, 30),
    averageSales: randomNum(5000, 20000),
    averageSalesGrowth: randomPercentage(-10, 25),
    averageOrders: randomNum(30, 120),
    averageOrdersGrowth: randomPercentage(-12, 28),
    averageCommission: randomNum(500, 2000),
    averageCommissionGrowth: randomPercentage(-8, 32)
  };
  
  // 生成分销商列表数据
  const generateDistributors = (count: number = 50) => {
    const levelMap: Record<string, string> = {
      '': '', // 所有等级
      'standard': 'standard',
      'premium': 'premium',
      'vip': 'vip'
    };
    
    const distributors = Array(count).fill(null).map((_, index) => {
      const randomLevel = ['standard', 'premium', 'vip'][Math.floor(Math.random() * 3)] as string;
      const distLevel = level ? levelMap[level] : randomLevel;
      
      // 如果指定了等级筛选，但当前生成的不匹配，则跳过
      if (level && distLevel !== levelMap[level]) {
        return null;
      }
      
      const sales = randomNum(1000, 100000);
      const orders = randomNum(10, 500);
      const commissionRate = randomNum(5, 15) / 100;
      const commission = Math.round(sales * commissionRate);
      
      return {
        id: `DS${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
        name: `分销商 ${String.fromCharCode(65 + index % 26)}${String.fromCharCode(65 + (index / 26) % 26)}`,
        avatar: `https://randomuser.me/api/portraits/${index % 2 ? 'men' : 'women'}/${(index % 70) + 1}.jpg`,
        level: distLevel,
        sales,
        orders,
        commission,
        customers: randomNum(5, 100),
        growth: randomPercentage(-20, 40)
      };
    }).filter(Boolean) as Array<{
      id: string;
      name: string;
      avatar: string;
      level: string;
      sales: number;
      orders: number;
      commission: number;
      customers: number;
      growth: number;
    }>; // 过滤掉null值并断言类型
    
    // 按销售额降序排序
    return distributors.sort((a, b) => b.sales - a.sales);
  };
  
  // 生成所有分销商数据
  const allDistributors = generateDistributors();
  
  // 取前10名用于业绩对比图表
  const comparisonData = allDistributors.slice(0, 10).map(dist => ({
    name: dist.name,
    sales: dist.sales,
    orders: dist.orders,
    commission: dist.commission,
    customers: dist.customers
  }));
  
  // 生成业绩趋势数据
  const generateTrends = () => {
    let days = 30;
    
    switch (period) {
      case 'week':
        days = 12; // 12周
        break;
      case 'month':
        days = 12; // 12个月
        break;
      default:
        days = 30; // 30天
    }
    
    const dates: string[] = [];
    const sales: number[] = [];
    const orders: number[] = [];
    const commission: number[] = [];
    
    const now = new Date();
    
    for (let i = 0; i < days; i++) {
      const date = new Date();
      
      if (period === 'day') {
        date.setDate(now.getDate() - (days - 1) + i);
        dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
      } else if (period === 'week') {
        date.setDate(now.getDate() - (days - 1) * 7 + i * 7);
        dates.push(`第${i + 1}周`);
      } else if (period === 'month') {
        date.setMonth(now.getMonth() - (days - 1) + i);
        dates.push(`${date.getMonth() + 1}月`);
      }
      
      // 生成波动的数据
      const baseSales = randomNum(80000, 120000);
      const factor = 0.8 + Math.sin(i / 5) * 0.3 + Math.random() * 0.2;
      
      const daySales = Math.round(baseSales * factor);
      const dayOrders = Math.round(daySales / randomNum(180, 220));
      const dayCommission = Math.round(daySales * randomNum(8, 12) / 100);
      
      sales.push(daySales);
      orders.push(dayOrders);
      commission.push(dayCommission);
    }
    
    return {
      dates,
      sales,
      orders,
      commission
    };
  };
  
  return {
    overview,
    distributors: allDistributors,
    comparison: comparisonData,
    trends: generateTrends()
  };
};

// 随机生成百分比
const randomPercentage = (min: number, max: number): number => {
  return parseFloat((Math.random() * (max - min) + min).toFixed(1));
};

// 导出所有生成函数
export default {
  generateAgentInfo,
  generateDashboard,
  generateDistributors,
  generateDistributorDetail,
  generateOrders,
  generateWithdrawals,
  generateDistributorWithdrawals,
  generateStatistics,
  generateDashboardOverviewData,
  generateSalesTrendData,
  generateDistributorsData,
  mockResponse,
  generateDistributorDetailData,
  generateDistributorSalesData,
  generateDistributorOrdersData,
  generateCommissionData,
  generateCommissionOverview,
  generateCommissionTrend,
  generateCommissionComposition,
  generateDistributorCommissionRanking,
  generateWithdrawalRecordsData,
  generateCommissionRulesData,
  generateSalesAnalyticsData,
  generateDistributorAnalyticsData
}; 